package com.jiang.service;

import com.jiang.Domain.Message;
import com.jiang.Domain.MessageType;
import com.jiang.Domain.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author Jiang
 * @version 1.0
 * @date 2023/11/29 10:50
 * 完成用户登录验证
 */
public class UserClientService {
    private User user = new User();
    private Socket socket;

    /**
     * 验证用户是否合法
     *
     * @param userId
     * @param pwd
     * @return
     */
    public boolean checkUser(String userId, String pwd) {
        boolean b = false;

        user.setId(userId);
        user.setPasswd(pwd);

        try {
            // 连接服务器，发送u对象
            socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(user);

            // 读取服务器回复的 Message 对象
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            Message message = (Message) objectInputStream.readObject();

            if (MessageType.MESSAGE_LOGIN_SUCCEED.equals(message.getMesType())) {
                // 创建一个和服务器保持通信的线程
                ClientConnectServerThread clientConnectServerThread = new ClientConnectServerThread(socket);
                new Thread(clientConnectServerThread).start();
                ManageClientConnectServerThread.addClientConnectServerThread(userId, clientConnectServerThread);

                b = true;
            } else {
                //如果登录失败，我们就不能启动和服务器通信的线程,关闭socket
                socket.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return b;
    }

    // 向服务端请求在线用户列表
    public void onlineFriedList() {
        Message message = new Message();
        message.setMesType(MessageType.MESSAGE_GET_ONLINE_FRIEND);
        message.setSender(user.getId());

        // 将Message 对象发送服务器， 得到当前线程的Socket对象的输出流
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(ManageClientConnectServerThread.getClientConnectServerThread(user.getId()).getSocket().getOutputStream());
            objectOutputStream.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 退出客户端，给服务端发送一个退出系统的message对象
    public void logout() {
        Message message = new Message();
        message.setMesType(MessageType.MESSAGE_CLIENT_EXIT);
        message.setSender(user.getId());

        // 发送message
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(message);
            System.out.println(user.getId() + " 退出系统");
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
